package com.apache.ius.impl;

import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.cache.service.CacheManager;
import com.apache.cache.service.impl.LoadCacheFactory;
import com.apache.cache.util.Validator;
import com.apache.database.constant.SystemTools;
import com.apache.database.model.Page;
import com.apache.tools.DataMap;
import com.apache.tools.StrUtil;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * IUS写缓存插件
 */
@Service("iusCachePlugin")
public class CachePluginImpl {
	protected Logger log = LoggerFactory.getLogger(getClass());
	/**
	 * 将结果集写入缓存
	 * @param vo
	 * @param entity
	 */
	public void writeCahce(ParamsVo vo , ResultEntity entity){
//		String cache_spaceName = sysEname+"_"+tableObjName+"_cache";
		String datasource = StrUtil.doNull(vo.getParamsToStr("datasource"),"plateform");
		String cacheKey = vo.getParamsToStr("resultSetCacheKey");//批定的缓存KEy
		if(Validator.isEmpty(entity.getEntity()) || StrUtil.isNull(cacheKey)){
			return ;
		}
		if(entity.getEntity() instanceof List || entity.getEntity() instanceof Map || entity.getEntity() instanceof Page) {
			if(cacheKey.indexOf("[")>-1){
				//特殊情况，及缓存数据的key是动态按表按字段的（把数据内的某字段值作为key）
				//格式一般是字段key-->DataMap
				String tableObjName = "";
				if(vo.getParams().containsKey("modelTypes")){
					String searchObjName = vo.getParamsToStr("modelTypes");
					tableObjName = searchObjName.split(",")[0].split("_")[1];//得到表对象
				}
				String cacheKeyVar = cacheKey.replace("[","").replace("]","");
				String newSpaceName = datasource+"_"+tableObjName+"_cache";
				String dataCacheKey = StrUtil.doNull(cacheKeyVar,"infoId");
				log.info("查询结果写入动态缓存["+newSpaceName+"]空间内，存储的数据是动态key["+dataCacheKey+"]");
				List<DataMap> dataList = new ArrayList<>();
				if(entity.getEntity() instanceof List){
					dataList = (List<DataMap>)entity.getEntity();
				}else if(entity.getEntity() instanceof Page){
					dataList = ((Page)entity.getEntity()).getPageObjects();
				}
				int count = dataList.size();
				String[] dataCacheKeyArr = dataCacheKey.split(",");
				SystemTools.getInstance().getCache(newSpaceName).removeAll();//重新追加最新的
				CacheManager cacheManager = LoadCacheFactory.getInstance().getCacheManager(newSpaceName);
				for (int i = 0; i < dataList.size(); i++) {
					Map dataMap = (Map) dataList.get(i),map=new HashMap<>();
					if(dataMap.containsKey(tableObjName)){
						map=(Map)dataMap.get(tableObjName);
					}else{
						map = dataMap;
					}
					String key = "";
					for(String k : dataCacheKeyArr){
						key+=String.valueOf(map.get(k))+"_";
					}
					if (key.length() > 1) {
						key = key.substring(0, key.length() - 1);
					}
					cacheManager.createCacheObject(key,map);
				}
				log.info("本次同步缓存["+count+"]条数据至缓存["+newSpaceName+"]完成！");
			}else{
				//默认情况，及缓存数据的key是固定的
				//格式一般是固定key-->List<DataMap>
				String spaceName = Validator.getDefaultStr(vo.getParamsToStr("cacheSpaceName"),"resDataCache");//指定的缓存空间
				String newSpaceName = datasource+"_"+spaceName;
				log.info("查询结果写入固定缓存["+newSpaceName+"]空间内，存储的数据是固定key["+cacheKey+"]");
				SystemTools.getInstance().getCache(newSpaceName).removeCacheObject(cacheKey);
				JSONObject json = new JSONObject();
				json.put("entity",entity.getEntity());
				log.info("结果写入缓存中。"+cacheKey+"->"+json.toString());
				SystemTools.getInstance().getCache(newSpaceName).createCacheObject(cacheKey, entity.getEntity());
			}
		}
	}
}
